﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using ThisIsELearning.Model;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ThisIsELearning.Learning.Controller
{
    /// <summary>
    /// Summary description for ContentManagementService
    /// </summary>
    [WebService(Namespace = "http://thisiselearning.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class ContentManagementService : System.Web.Services.WebService
    {
        [WebMethod]
        public string uploadMedia()
        {
            string mediaType = HttpContext.Current.Request["mediaType"];
            string dirToStore = "";
            switch (mediaType)
            {
                case "ImageObject":
                case "image":
                case "Image":
                    dirToStore = "res/image";
                    break;

                case "AudioObject":
                case "audio":
                case "Audio":
                    dirToStore = "res/audio";
                    break;

                case "VideoObject":
                case "video":
                case "Video":
                    dirToStore = "res/video";
                    break;
            }

            if (!Directory.Exists(Server.MapPath("~/" + dirToStore)))
                Directory.CreateDirectory(Server.MapPath("~/" + dirToStore));

            HttpPostedFile theFile = HttpContext.Current.Request.Files["mediaToUpload"];

            string ext = Path.GetExtension(Path.GetFileName(theFile.FileName));
            string fname = DataManagerHelper.generateRandomFileName(ext.Substring(1));
            string fullpath = Server.MapPath(Path.Combine("~/" + dirToStore + "/", fname));
            while (File.Exists(fullpath))
            {
                fname = DataManagerHelper.generateRandomFileName(ext.Substring(1));
                fullpath = Server.MapPath(Path.Combine("~/" + dirToStore + "/", fname));
            }

            theFile.SaveAs(Server.MapPath(Path.Combine("~/" + dirToStore + "/", fname)));

            return "success;" + fname;
        }

        [WebMethod]
        public string commitCanvas()
        {
            try
            {
                string jsonString = HttpContext.Current.Request["serializedObjects"];
                string canvasIdStr = HttpContext.Current.Request["canvasId"];
                if (jsonString == null || canvasIdStr == null)
                    return "failed";

                int canvasId = Convert.ToInt32(canvasIdStr);

                JavaScriptSerializer js = new JavaScriptSerializer();
                CanvasObjectsArray objects = js.Deserialize<CanvasObjectsArray>(jsonString);

                var q = DataManagerHelper.getDataManager().ContentCanvas.Where(a => a.contentCanvasId == canvasId);
                if (!q.Any())
                    return "failed";

                ContentCanvas canvas = q.First();
                List<ItemObjectType> itemObjectTypes = DataManagerHelper.listAllItemObjectTypes();

                foreach (var x in objects.textObjects)
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    MemoryStream mstream = new MemoryStream();

                    bf.Serialize(mstream, x);

                    CanvasItem canvasItem = new CanvasItem
                    {
                        contentCanvas = canvas,
                        itemObjectType = itemObjectTypes[0],
                        itemObjectData = mstream.ToArray()
                    };

                    DataManagerHelper.getDataManager().AddToCanvasItems(canvasItem);
                }

                DataManagerHelper.getDataManager().SaveChanges();
            }
            catch (Exception ex)
            {
                return "failed;" + ex.StackTrace;
            }

            return "done";
        }

        [WebMethod]
        public string addNewCanvas()
        {
            return "";
        }
    }

    public class CanvasObjectsArray
    {
        public CanvasTextBlock[] textObjects { set; get; }
        public CanvasAudio[] audioObjects { set; get; }
        public CanvasVideo[] videoObjects { set; get; }
        public CanvasImage[] imageObjects { set; get; }
    }

}
